<?php
namespace app\console\controller;
use app\console\model\Admin as SelfModel;
use app\console\model\Role as RoleModel;
use app\console\model\AdminRole as AdminRoleModel;
use think\facade\Request;
use think\facade\Route;
use think\facade\View;
use think\facade\Db;
use think\facade\Response;

class Admin extends Base
{


    public function index()
    {

        $data = SelfModel::alias('admin')
            ->join('admin_role', 'admin.id = admin_role.admin_id', 'LEFT')
            ->join('role', 'admin_role.role_id = role.id', 'LEFT')
            ->field('admin.id,admin_name,admin.data_id_str,multi_pic,GROUP_CONCAT(role_name) role_name,admin.sort,admin.status')
            ->group('admin.id')
            ->paginate(10)->each(function ($item,$key){
                //$item->list = ['titles'=>''];
                $item->list = (new \app\model\Company())->field('GROUP_CONCAT(title) titles')->where('id','in',$item['data_id_str'])->find();
            });

        return View::fetch('', ['data' => $data]);
    }





    public function create()
    {

        if ($this->request->isPost()) {
            $inquire = $this->request->param();

            $ret = (new SelfModel())->save($inquire);
            if ($ret) {
                win('操作成功', Route::buildUrl('index'));
            }
            win('操作失败');
        }
        $role_data = RoleModel::where('status',1)->select();
        return View::fetch('',['role_data' => $role_data]);
    }


    public function update()
    {
        $id = input('id');
        $info = SelfModel::find($id);
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $ret = $info->save($param, $id);
            if ($ret !== false) {
                jump('修改成功', Route::buildUrl('index'));
            }
            fail('修改失败');
        }
        $role_data = RoleModel::where('status',1)->select();
        $roleId = AdminRoleModel::field('GROUP_CONCAT(role_id) role_id')->where('admin_id',$id)->find();
        return View::fetch('create', ['info' => $info,'role_data' => $role_data,'role_id' => $roleId['role_id']]);
    }

    public function destory($id)
    {
        if ($this->request->isGet()) {
            $ret = SelfModel::destroy($id);

            if($id == 1){
                fail('超级管理员不能删除');
            }
            if ($ret){
                win('删除成功', Route::buildUrl('index'));
            }
            fail('删除失败');
        }
    }

    public function check()
    {
        $inquire = $this->request->param();
        $ret = SelfModel::where('id', $inquire['id'])->value($inquire['check']) == '1' ? 2 : 1;
        if (SelfModel::where('id', $inquire['id'])->update([$inquire['check'] => $ret])) {
            return $ret;
        }
        return false;
    }


}